//
//  LXActionSheet.m
//  LXActionSheet
//
//  Created by lachesis-zhu on 16/4/26.
//  Copyright © 2016年 xiao.zhao@lachesis-mh.com. All rights reserved.
//

#import "LXActionSheet.h"
#import "LXActionCell.h"

@interface LXActionSheet () <UITableViewDataSource , UITableViewDelegate , UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSArray *listData;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) UIView *customerView;
@property (nonatomic, assign) ShowDirection showDirection;
@property (nonatomic, assign) NSInteger cancleHeight;
@end

@implementation LXActionSheet

- (id)initWithTitle:(NSString *)title delegate:(id<LXActionSheetDelegate>)delegate direction:(ShowDirection)direction cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)titlesArray{
    if (self = [super init]) {
        self.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        self.backgroundColor = RGBACOLOR(160, 160, 160, 0);
        
        _delegate = delegate;
        
        _customerView = [[UIView alloc] init];
        _customerView.backgroundColor = [UIColor clearColor];
        [self addSubview:_customerView];
        
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _customerView.lx_width, 0) style:UITableViewStylePlain];
        _tableview.dataSource = self;
        _tableview.delegate = self;
        _tableview.scrollEnabled = NO;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_customerView addSubview:_tableview];
        
        if (cancelButtonTitle != nil && ![cancelButtonTitle isEqualToString:@""]) {
            _cancleHeight = 80;
            UILabel *cancelLabel = [[UILabel alloc] init];
            cancelLabel.layer.cornerRadius = 5;
            cancelLabel.layer.backgroundColor = [UIColor whiteColor].CGColor;
            
            cancelLabel.text = cancelButtonTitle;
            cancelLabel.font = [UIFont lx_systemFontOfSize:20];
            cancelLabel.textAlignment = NSTextAlignmentCenter;
            cancelLabel.textColor = kAppNormalTextColor;
            UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedCancel)];
            cancelLabel.userInteractionEnabled = YES;
            [cancelLabel addGestureRecognizer:tapRecognizer];
            [_customerView addSubview:cancelLabel];
        }
        
        _listData = titlesArray;
        _title = title;
        _showDirection = direction;
    }
    return self;
}

- (void)setCornerRadius:(NSInteger)cornerRadius
{
    _cornerRadius = cornerRadius;
}

- (void)setOffsetHeight:(NSInteger)offsetHeight
{
    _offsetHeight = offsetHeight;
}

- (void)setOffsetWeight:(NSInteger)offsetWeight
{
    _offsetWeight = offsetWeight;
}

- (void)drawRect:(CGRect)rect
{
    
}

//如果tableview处于uiview上面，uiview整个背景有点击事件，但是我们需要如果我们点击tableview的时候，处理tableview的点击事件，而不是uiview的事件。在这里，我们需要判断我们点击事件是否在uiview上还是在uitableview上。
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[self class]]) {
        return YES;
    }
    return NO;
}

- (void)animeData {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedCancel)];
    tapGesture.delegate = self;
    [self addGestureRecognizer:tapGesture];
    self.userInteractionEnabled = YES;
    
    NSArray *viewsArray = [_customerView subviews];
    __block UILabel *cancleLabel;
    [viewsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[UILabel class]]) {
            cancleLabel = obj;
        }
    }];
    
    _tableview.layer.cornerRadius = _cornerRadius;
    if (_showDirection == TopShowDirection) {
        _customerView.frame = CGRectMake([LXAutoLength lx_L:_offsetWeight], _offsetHeight, ScreenWidth - [LXAutoLength lx_L:_offsetWeight] * 2, 0);
    } else {
        _customerView.frame = CGRectMake([LXAutoLength lx_L:_offsetWeight], ScreenHeight - _offsetHeight, ScreenWidth - [LXAutoLength lx_L:_offsetWeight] * 2, 0);
    }
    _tableview.frame = CGRectMake(0, 0, _customerView.lx_width, 0);
    cancleLabel.frame = CGRectMake(0, [LXAutoLength lx_L:60] * [_listData count] + [LXAutoLength lx_L:10], _customerView.lx_width, 0);
    
    [UIView animateWithDuration:0.25f animations:^{
        self.backgroundColor = RGBACOLOR(160, 160, 160, 0.4);
        
        if (_showDirection == TopShowDirection) {
            _customerView.frame = CGRectMake(_customerView.lx_originX, _customerView.lx_originY, _customerView.lx_width, [LXAutoLength lx_L:60] * [_listData count] + [LXAutoLength lx_L:_cancleHeight]);
            _tableview.frame = CGRectMake(0, 0, _customerView.lx_width, [LXAutoLength lx_L:60] * [_listData count]);
            cancleLabel.frame = CGRectMake(0, [LXAutoLength lx_L:60] * [_listData count] + [LXAutoLength lx_L:10], _customerView.lx_width, [LXAutoLength lx_L:60]);
        } else {
             _customerView.frame = CGRectMake(_customerView.lx_originX, _customerView.lx_originY - [LXAutoLength lx_L:_cancleHeight] - [LXAutoLength lx_L:60] * [_listData count], _customerView.lx_width, [LXAutoLength lx_L:60] * [_listData count] + [LXAutoLength lx_L:_cancleHeight]);
            _tableview.frame = CGRectMake(0, 0, _customerView.lx_width, [LXAutoLength lx_L:60] * [_listData count]);
            cancleLabel.frame = CGRectMake(0, [LXAutoLength lx_L:60] * [_listData count] + [LXAutoLength lx_L:10], _customerView.lx_width, [LXAutoLength lx_L:60]);
        }
    } completion:^(BOOL finished) {
        
    }];
}

- (void)tappedCancel {
    [UIView animateWithDuration:.25 animations:^{
        self.alpha = 0;
        if (_showDirection == TopShowDirection) {
            _customerView.frame = CGRectMake([LXAutoLength lx_L:_offsetWeight], _offsetHeight, ScreenWidth - [LXAutoLength lx_L:_offsetWeight] * 2, 0);
        } else {
            _customerView.frame = CGRectMake([LXAutoLength lx_L:_offsetWeight], ScreenHeight - _offsetHeight, ScreenWidth - [LXAutoLength lx_L:_offsetWeight] * 2, 0);
        }
        _tableview.frame = CGRectMake(0, 0, _customerView.lx_width, 0);
    } completion:^(BOOL finished) {
        if (finished) {
            for (UIView *v in _customerView.subviews) {
                [v removeFromSuperview];
            }
            [_customerView removeFromSuperview];
        }
    }];
}

- (void) showInView:(UIView *)view{
    if (view) {
        [view addSubview:self];
    } else {
        [[UIApplication sharedApplication].delegate.window.rootViewController.view addSubview:self];
    }
    [self animeData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_title && ![_title isEqualToString:@""]) {
        return [_listData count] + 1;
    } else {
        return [_listData count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [LXAutoLength lx_L:60];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_title && ![_title isEqualToString:@""]) {
        if (indexPath.row == 0) {
            static NSString *cellIdentifier = @"TitleCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell==nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            cell.textLabel.text = _title;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.userInteractionEnabled = NO;
            return cell;
        } else {
            static NSString *cellIdentifier = @"DownSheetCell";
            LXActionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell==nil) {
                cell = [[LXActionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            [cell setData:[_listData objectAtIndex:indexPath.row - 1]];
            [cell.contentView drawAroundViewWithLocation:DrawBottom color:kAppLinesColor insets:UIEdgeInsetsMake(-0.5, 0, 0, 0)];
            return cell;
        }
    } else {
        static NSString *cellIdentifier = @"DownSheetCell";
        LXActionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell==nil) {
            cell = [[LXActionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        [cell setData:[_listData objectAtIndex:indexPath.row]];
        [cell.contentView drawAroundViewWithLocation:DrawBottom color:kAppLinesColor insets:UIEdgeInsetsMake(-0.5, 0, 0, 0)];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self tappedCancel];
    if (_delegate != nil && [_delegate respondsToSelector:@selector(LXActionSheet:didSelectIndex:)]) {
        [_delegate LXActionSheet:self didSelectIndex:indexPath.row];
        return;
    }
}

@end
